package org.example.strategy;

import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 自定义范围分片算法
 * @author shenguangyang
 */
public class CustomRangeShardingAlgorithm implements RangeShardingAlgorithm<Long> {

    /**
     *
     * @param dataSourceNames 数据源集合
     *                   在分库时值为所有分片库的集合
     *                   分表时为对应分片库中所有分片表的集合
     * @param rangeShardingValue 分片属性, 包括
     *                             loginTableName: 逻辑表
     *                             columnName: 分片键(字段)
     *                             value: 为从SQL中解析出的分片键的值
     */
    @Override
    public Collection<String> doSharding(Collection<String> dataSourceNames, RangeShardingValue<Long> rangeShardingValue) {
        Set<String> result = new LinkedHashSet<>();
        // between 起始值
        long lower = rangeShardingValue.getValueRange().lowerEndpoint();
        // between 结束值
        long upper = rangeShardingValue.getValueRange().upperEndpoint();
        // 循环计算分库逻辑
        for (long i = lower; i <= upper; i++) {
            for (String dataSourceName : dataSourceNames) {
                if (dataSourceName.endsWith(i % dataSourceNames.size() + "")) {
                    result.add(dataSourceName);
                }
            }
        }
        return result;
    }
}
